package es.mgil.blog;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

@SuppressWarnings("serial")
public class BlogServletM extends HttpServlet {
	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		// La respuesta sera en texto
		resp.setContentType("text");
		resp.setCharacterEncoding("utf-8");
		PrintWriter out = resp.getWriter();
		int op = -1;
		try {
			op = Integer.parseInt(req.getParameter("op"));
		} catch (Exception e) {
			out.println("Bad URL");
			return;
		}

		PersistenceManager pm = PMF.get().getPersistenceManager();

		switch (op) {
		case 1: // Listar mensajes
			String query = "select from " + Mensaje.class.getName();
			List<Mensaje> mensajes = (List<Mensaje>) pm.newQuery(query)
					.execute();
			Gson gson = new GsonBuilder().setPrettyPrinting()
					.setDateFormat("dd-MM-yyyy HH:mm").create();
			String json = gson.toJson(mensajes);
			out.println(json);
			break;
		case 2: // Nuevo mensaje
			String user = req.getParameter("user");
			if (user == null) {
				out.println("Missing user");
				return;
			}
			User u = new User(user, user);

			String title = req.getParameter("title");
			if (title == null) {
				out.println("Missing title");
				return;
			}

			String content = req.getParameter("content");
			if (content == null) {
				out.println("Missing content");
				return;
			}

			Date date = new Date();

			Mensaje mensaje = new Mensaje(u, title, content, date);
			try {
				pm.makePersistent(mensaje);
			} finally {
				pm.close();
			}
			out.println("Message has been sent");
			break;
		case 3:
			String id = req.getParameter("id");
			if (id == null) {
				out.println("Missing message ID");
				return;
			}

			long idL = -1;
			try {
				idL = Long.parseLong(id);
			} catch (Exception e) {
				out.println("Introduced ID is not a valid number");
				return;
			}

			Mensaje msg = null;
			try {
				msg = pm.getObjectById(Mensaje.class, idL);
			} catch (Exception e) {
				out.println("Identifier not found");
				return;
			}

			try {
				pm.deletePersistent(msg);
			} finally {
				pm.close();
			}

			break;
		}
	}
}
